﻿/*
 * This file is part of MonoStrategy.
 *
 * Copyright (C) 2010-2011 Christoph Husse
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors: 
 *      # Christoph Husse
 * 
 * Also checkout our homepage: http://monostrategy.codeplex.com/
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MonoStrategy
{
    public class ToolSmithBuilding : InputOutputBuilding
    {
        internal ToolSmithBuilding(BuildingManager inParent, BuildingConfig inConfig, Point inPosition)
            :base(inParent, inConfig, inPosition)
        {
        }

        protected override ProviderSelection SelectProvider()
        {
            // process todos first
            foreach(var prov in Providers)
            {
                var config = Parent.Map.Config.Tools[prov.Resource];

                if ((config.Todo > 0) && prov.HasSpace)
                {
                    return new ProviderSelection()
                    { 
                        Provider = prov,
                        OnProduced = () => { config.Todo--; },
                    };
                }
            }

            double totalProb = 0;
            GenericResourceStack result = null;

            foreach (var prov in Providers)
            {
                if (!prov.HasSpace)
                    continue;

                totalProb += Parent.Map.Config.Tools[prov.Resource].Percentage;
            }

            if (totalProb > 0)
            {
                double val = m_Random.NextDouble() * totalProb;
                double lastProb = 0;

                totalProb = 0;

                foreach (var prov in Providers)
                {
                    if (!prov.HasSpace)
                        continue;

                    lastProb = totalProb;
                    totalProb += Parent.Map.Config.Tools[prov.Resource].Percentage;

                    if ((lastProb <= val) && (val <= totalProb))
                    {
                        result = prov;
                        break;
                    }
                }
            }

            return new ProviderSelection()
            { 
                Provider = result,
            };
        }
    }
}
